<template>
  <div class="box">
    <!-- 筛选导航栏! -->
    <el-form style="text-align: left" :inline="true">
      <el-form-item label="商品:">
        <el-input
          placeholder="请输入需要查询的商品名称:"
          v-model="form.name"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchData">搜索</el-button>
        <el-button type="danger" @click="emptyData">清空</el-button>
      </el-form-item>
    </el-form>
    <!-- 按钮导航栏! -->
    <div class="buttonNavigation">
      <el-button type="primary" @click="addGoodsInfo">新增商品信息</el-button>
    </div>
    <!-- 列表展示栏! -->
    <el-table :data="dataList" border stripe style="width: 100%">
      <el-table-column
        label="序号"
        align="center"
        :show-overflow-tooltip="true"
      >
        <template scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="name"
        label="商品名称"
        align="center"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        prop="realPrice"
        label="实际价格（人民币）"
        align="center"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        prop="sellPrice"
        label="售卖价格（积分）"
        align="center"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        prop="stock"
        label="库存"
        align="center"
        :show-overflow-tooltip="true"
      />
      <!-- <el-table-column
        prop="name"
        label="商品名称"
        align="center"
        :show-overflow-tooltip="true"
      /> -->
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button @click="editor(scope)" type="text">编辑</el-button>
          <el-popconfirm
            title="确定删除这条数据么?"
            @onConfirm="Malldelete(scope)"
          >
            <el-button slot="reference" type="text" style="color: #fb575e"
              >删除</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页导航栏! -->
    <div class="pagination">
      <span class="title">小计：共{{ this.total }}条数据</span>
      <el-pagination
        background
        layout="total,prev, pager, next, sizes"
        :total="total"
        :page-size="form.pageSize"
        :current-page.sync="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      >
      </el-pagination>
    </div>
    <!-- 弹窗导航栏! -->
    <el-dialog
      :title="dialogVisibleTitle"
      :visible.sync="dialogVisible"
      width="40%"
      :before-close="handleClose"
    >
      <!-- -->
      <el-form :inline="true" style="text-align: left">
        <el-form-item label="商品名称:" label-width="150px">
          <el-input v-model="goodsForm.name"></el-input>
        </el-form-item>
        <el-form-item label="实际价格(人民币):" label-width="150px">
          <el-input v-model="goodsForm.realPrice"></el-input>
        </el-form-item>
        <el-form-item label="售卖价格(积分):" label-width="150px">
          <el-input v-model="goodsForm.sellPrice"></el-input>
        </el-form-item>
        <el-form-item label="库存:" label-width="150px">
          <el-input v-model="goodsForm.stock"></el-input>
        </el-form-item>
        <el-form-item label="商品图片" label-width="150px">
          <!-- <el-input v-model="goodsForm.url"></el-input> -->
          <el-upload
            class="upload-demo"
            action=""
            ref="uploadImg"
            :multiple="false"
            accept=""
            :http-request="upload"
            :on-change="imgHandlerChange"
            :on-remove="imgHandlerRemove"
            :file-list="imgFileList"
            list-type="picture"
            :limit="1"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <span style="color: red">*商品图片只能上传一张</span>
          </el-upload>
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="submitGoodsInfo">提交</el-button>
      <el-button type="primary" @click="this.handleClose">取消</el-button>
    </el-dialog>
  </div>
</template>
<script>
import {
  getMallCommodityList,
  MallImgCode,
  addMall,
  deleteMall,
  queryMall,
  modifyMall,
} from "../../assets/js/api";
export default {
  data() {
    return {
      form: {
        name: "",
        pageNo: 1,
        pageSize: 10,
      },
      currentPage: 1,
      dataList: [],
      total: null,
      dialogVisibleTitle: "",
      dialogVisible: false,
      imgFileList: [],
      goodsForm: {
        id: null,
        name: "",
        realPrice: "",
        sellPrice: "",
        stock: "",
        url: "",
      },
      ossUrl: "",
      formData: {},
    };
  },
  created() {
    this.getCommodityList();
  },
  methods: {
    //获取商品信息列表!
    getCommodityList() {
      getMallCommodityList(this.form).then((res) => {
        this.dataList = res.data.records;
        this.total = res.data.total;
      });
    },
    // 搜索按钮!
    searchData() {
      this.form.pageNo = 1;
      this.getCommodityList();
    },
    // 清空按钮!
    emptyData() {
      this.form.name = "";
      this.getCommodityList();
    },
    //分页
    handleCurrentChange(cpage) {
      this.form.pageNo = cpage;
      this.getCommodityList();
    },
    handleSizeChange(psize) {
      this.form.pageSize = psize;
      this.getCommodityList();
    },
    // 新增商品信息按钮!
    addGoodsInfo() {
      this.goodsForm.name = "";
      this.goodsForm.realPrice = "";
      this.goodsForm.sellPrice = "";
      this.goodsForm.stock = "";
      this.goodsForm.url = "";
      this.imgFileList = [];
      this.dialogVisible = true;
      this.dialogVisibleTitle = "新增商品信息";
    },
    upload() {},
    // 提交按钮!
    async uploadToOss(params, fieldName) {
      var dataOss = "";
      var suffix = "";
      await MallImgCode().then((res) => {
        let imgName = params.name; //图片全名字!
        suffix = imgName.split(".");
        suffix = suffix[suffix.length - 1]; //图片类型!
        let wz = imgName.split(".");
        let imgType = "." + wz[wz.length - 1];
        //创建文件
        let formData = new FormData();
        //上传对象
        dataOss = res.data;
        let ossUrl = dataOss.host;
        formData.append("policy", dataOss.policy);
        formData.append("key", dataOss.dir + dataOss.fileName + imgType);
        formData.append("OSSAccessKeyId", dataOss.accessid);
        formData.append("Signature", dataOss.signature);
        formData.append("success_action_status", 200);
        formData.append("fileName", dataOss.fileName);
        formData.append("file", params.raw);
        let fileForm = {
          showName: imgName,
          url: dataOss.fileName,
          size: params.size,
          sid: this.id,
          type: this.uplodType,
        };
        this.fileForm = fileForm;
        this.formData = formData;
        this.ossUrl = ossUrl;
      });
      await this.axios
        .post(this.ossUrl, this.formData, this.config)
        .then((res) => {
          if (res.status == 200) {
            this.goodsForm[fieldName] =
              "https://file.xssbdc.com/" +
              dataOss.dir +
              dataOss.fileName +
              "." +
              suffix;
          }
        });
    },
    async submitGoodsInfo() {
      if (this.imgFileList.length > 0 && this.goodsForm.url == "") {
        await this.uploadToOss(this.imgFileList[0], "url");
      }
      if (
        this.goodsForm.name == "" ||
        this.goodsForm.realPrice == "" ||
        this.goodsForm.sellPrice == "" ||
        this.goodsForm.stock == "" ||
        this.goodsForm.url == ""
      ) {
        this.$message.error("请先完善信息!");
      } else {
        if (this.dialogVisibleTitle == "新增商品信息") {
          addMall(this.goodsForm).then((res) => {
            if (res.code == 200) {
              this.$message.success(res.message);
              this.dialogVisible = false;
              this.dialogVisibleTitle = null;
              this.getCommodityList();
              this.imgFileList = [];
            } else {
              this.$message.error(res.message);
            }
          });
        } else {
          if (this.dialogVisibleTitle == "修改商品信息") {
            modifyMall(this.goodsForm).then((res) => {
              if (res.code == 200) {
                this.$message.success(res.message);
                this.dialogVisible = false;
                this.dialogVisibleTitle = null;
                this.imgFileList = [];
                this.getCommodityList();
              } else {
                this.$message.error(res.message);
              }
            });
          }
        }
      }
    },
    // 图片改变时的钩子!
    imgHandlerChange(file, fileList) {
      this.imgFileList = fileList;
    },
    // 图片上传移除的钩子!
    imgHandlerRemove(file, fileList) {
      this.imgFileList = fileList;
      this.goodsForm.url = "";
    },
    // 新增修改弹窗监听事件!
    handleClose() {
      this.goodsForm.url = "";
      this.goodsForm.name = "";
      this.goodsForm.realPrice = "";
      this.goodsForm.sellPrice = "";
      this.goodsForm.stock = "";
      this.goodsForm.id = null;
      this.dialogVisible = false;
      this.imgFileList = [];
    },
    // 详情按钮!
    editor(data) {
      queryMall(data.row.id).then((res) => {
        if (res.code == 200) {
          this.dialogVisible = true;
          this.dialogVisibleTitle = "修改商品信息";
          this.goodsForm = res.data;
          this.imgFileList.push({
            name: res.data.url.split("/")[res.data.url.split("/").length - 1],
            url: res.data.url,
          });
        }
      });
    },
    // 删除按钮!
    Malldelete(data) {
      deleteMall(data.row.id).then((res) => {
        if (res.code == 200) {
          this.$message.success(res.message);
          this.getCommodityList();
        } else {
          this.$message.error(res.message);
        }
      });
    },
  },
};
</script>
<style lang="less" scoped>
.box
{
    position: relative;  padding: 20px;  background-color: #fff;
}
::v-deep .el-pagination__total
{
    visibility: hidden;
}
::v-deep .el-pagination
{
    position: absolute;  right: 0;
 margin-top: 20px; 
}
.title
{ font-family: Microsoft YaHei;  font-size: 12px;  font-weight: 400;  line-height: 21px;

    position: absolute;  left: 0;  margin-top: 15px;  color: rgba(51, 51, 51, 1); 
}
.buttonNavigation
{ margin-bottom: 10px;

    text-align: left; 
}

</style>